//
//  WBNetworkManager.swift
//  传智微博
//
//  Created by FYXJ（6） on 2018/9/4.
//  Copyright © 2018年 FYXJ（6）. All rights reserved.
//

import UIKit
import AFNetworking

enum WBHTTPMethod {
    case GET
    case POST
}
/// 网络管理工具
class WBNetworkManager: AFHTTPSessionManager {

    
    
    static let shared = WBNetworkManager()
    
    var accessToken: String? = "2.00q6MmHDZ_8y8D2cde03944d00yTIJ"
    func tokenRequest(method: WBHTTPMethod = .GET,URLString: String,parameters: [String: AnyObject]?, completion: @escaping (_ json: AnyObject?,_ isSuccess:Bool) ->()) {


        guard let token = accessToken else {

            completion(nil,false)
            return
        }

        var parameters = parameters
        if parameters == nil {
            parameters = [String: AnyObject]()
        }
        parameters!["access_token"] = token as AnyObject

        request(method: method, URLString: URLString, parameters: parameters, completion: completion)
    }
    
    func request(method: WBHTTPMethod = .GET,URLString: String,parameters: [String: AnyObject]?, completion: @escaping (_ json: AnyObject?,_ isSuccess:Bool) ->()) {
        
        let success = { (task:URLSessionDataTask,json:Any?)->() in
            completion(json as AnyObject,true)
        }
        let failure = { (task:URLSessionDataTask?,error:Error)->() in

            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {

            }
            completion(nil,false)
        }

        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        else
        {
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }

    }
}
